package cn.xingzhe.monster.user.infrastructure.service;

import cn.dev33.satoken.stp.StpUtil;
import cn.xingzhe.monster.user.domain.service.AuthenticationService;
import org.springframework.stereotype.Component;

/**
 * 认证服务实现
 * 基于sa-token实现用户认证
 *
 * @author System
 * @version 1.0.0
 * @since 2024-01-01
 */
@Component
public class StpAuthenticationService implements AuthenticationService {

    @Override
    public String login(String userId) {
        StpUtil.login(userId);
        return StpUtil.getTokenValue();
    }

    @Override
    public void logout(String userId) {
        StpUtil.logout(userId);
    }

    @Override
    public String getCurrentToken() {
        try {
            return StpUtil.getTokenValue();
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public String getCurrentUserId() {
        try {
            return StpUtil.getLoginIdAsString();
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public boolean isLoggedIn(String userId) {
        try {
            return StpUtil.isLogin() && StpUtil.getLoginIdAsString().equals(userId);
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean isCurrentUserLoggedIn() {
        try {
            return StpUtil.isLogin();
        } catch (Exception e) {
            return false;
        }
    }
}

